package www.ld.com.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import www.ld.com.domain.R;

@Component
@Slf4j
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity<R> translate(Exception e) throws Exception {
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (int i = 0; i < stackTrace.length; i++) {
            System.out.println(stackTrace[i]);
        }
        log.error("请求异常：{}", e.getStackTrace());
        if (e instanceof InvalidTokenException) {
            return ResponseEntity.status(HttpStatus.OK).body(R.unauthorized());
        }
        if (e instanceof InvalidGrantException) {
            return ResponseEntity.status(HttpStatus.OK).body(R.error("认证失败：" + e.getMessage()));
        }
        if (e instanceof InternalAuthenticationServiceException) {
            return ResponseEntity.status(HttpStatus.OK).body(R.error("认证失败：用户名不存在！"));
        }
        return ResponseEntity.status(HttpStatus.OK).body(R.error("请求异常：联系管理员！"));
    }
}
